<?php

namespace App\Console\Commands;


use App\Listeners\Listener;

use App\Model\Eeoapi\Eeostudent;

use Illuminate\Console\Command;


class Students extends Command
{

    /**
     * sync pre-hour
     *
     */

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:Students';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync EEO studentId';

    /**
     * Create a new command instance.
     *
     * @return void
     */


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try{
            $this->getStudents();
            echo "Sync students info Succeed";
        }catch (\Exception $e){
            echo "Sync students info Failed :".$e->getMessage();
        }
    }

    /**
     * 查询所有已结束课节学生的评价
     * @param
     */
    protected function getStudents()
    {
        $this->syncStudents();
    }


    /**
     * 拉取EEO学生id
     * @param $page 页数
     */
    protected function syncStudents($page = 1)
    {
        try{
            $listener = new Listener();
            $listener->setUri('getStudentList');
            $data = $listener->dataMaker();
            $data['page'] = $page;
            $data['perpage'] = 100;
            $listener->setRequest($data);
            $result = $listener->callEeoApi();
            if($result['error_info']['errno'] == 1) {
                if(count($result['data']) < 100){
                    $this->saveData($result['data']);
                }else{
                    $this->syncStudents($page+1);
                }
            }else{
                throw new \Exception($result['error_info']['error'],$result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 存储同步数据到数据库
     * @param $ClassInNo EEO学生账号
     * @param $studentId EEO学生Id
     */
    public function saveData($data)
    {
        try{
            foreach ($data as $item){

                $fileds = [
                    'ClassInNo'=>$item['student_account'],
                    'studentId'=>$item['studentId']
                ];
                Eeostudent::firstOrCreate($fileds);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

}
